
--[[
    一个mysql的服务池

]]


local M = class("Manager")


function M:ctor(conf_name)
    self.conf_name = conf_name or "rabbit" --配置名
    self.services = {}
    self.sid = 1 --当前使用的服务id
    self:initServices()
    self:register()
end

function M:register()
    g.register("send", handler(self, self.send))
    g.register("call", handler(self, self.call))

    g.register("send_user", handler(self, self.sendUser))
    g.register("call_user", handler(self, self.callUser))
end


--
function M:initServices()
    for i=1, g.const.rabbit_worker_num do
        local service = g.newServiceStart("rabbitpub.agent.service", self.conf_name)
        if service then 
            table.insert(self.services, service)
        else
            --连接失败了(让程序强制退出)
            g.log:err("can't connect redis id:", i)
        end
    end
end

function M:send(...)
    self.sid = self.sid % #self.services + 1
    local service = self.services[self.sid]
    return g.send(service, ...)
end

function M:call(...)
    self.sid = self.sid % #self.services + 1
    local service = self.services[self.sid]
    return g.call(service, ...)
end

--通过id返回对应的service
function M:getServiceWithId(id)
    local sid =  id % #self.services + 1
    local service = self.services[self.sid]
    return service
end

function M:sendUser(uid, ...)
    local sid = uid % #self.services + 1
    local service = self.services[sid]
    return g.send(service, ...)
end

function M:callUser(uid, ...)
    local sid = uid % #self.services + 1
    local service = self.services[sid]
    return g.call(service, ...)
end


return M